package com.ftl.games;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.ImageView;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import com.ftl.games.SessionEvents.AuthListener;
import com.ftl.games.SessionEvents.LogoutListener;

public class FBLogin extends Activity {
	
	protected String imagenFinal = "";
    private LoginButton btnLoginFB;
    private Facebook mFacebook;
    private AsyncFacebookRunner mAsyncRunner;
    protected Uri uri;
    protected Runnable viewOrders;
    protected ProgressDialog m_ProgressDialog;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
	  //Cambio de pantalla
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        setContentView(R.layout.login);
	
		Bundle params = getIntent().getExtras();
		
		imagenFinal = params.getString("imagenFinal");
		uri = Uri.parse(params.getString("uri"));
		
	    //Busco donde va a ir la imagen
		ImageView imagen = (ImageView) findViewById(R.id.Foto);
		btnLoginFB = (LoginButton) findViewById(R.id.login);
		
	    //Redimensiono el ImageView para ver un Thumb
		imagen.getLayoutParams().width = 240;
	    imagen.getLayoutParams().height = 240;
	    imagen.setImageURI(uri);
	    
	    mFacebook = new Facebook(Config.FB_APP_ID);
	   	mAsyncRunner = new AsyncFacebookRunner(mFacebook);
	
	    SessionStore.restore(mFacebook, this);
	    SessionEvents.addAuthListener(new SampleAuthListener());
	    SessionEvents.addLogoutListener(new SampleLogoutListener());
	    btnLoginFB.init(this, mFacebook, Config.FB_APP_PERMISSIONS);
	    
	    
	    if (mFacebook.isSessionValid())
	    {
		     viewOrders = new Runnable(){
	          @Override
	          public void run() {
	        	  mAsyncRunner.request("me", new InfoRequestListener());
	          }
	      };
	      Thread thread =  new Thread(null, viewOrders, "MagentoBackground");
	      thread.start();
	      m_ProgressDialog = ProgressDialog.show(FBLogin.this, "Please wait...", "Retrieving data ...", true);
	    	
	    }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
        mFacebook.authorizeCallback(requestCode, resultCode, data);
    }
    
    public class SampleAuthListener implements AuthListener {

        public void onAuthSucceed() {
           // txtEstado.setText("You have logged in! ");
        	FBLogin.this.runOnUiThread(new Runnable() {
            	public void run() {
		        	viewOrders = new Runnable(){
		  	          @Override
		  	          public void run() {
		  	        	  mAsyncRunner.request("me", new InfoRequestListener());
		  	          }
		  	      };
		  	      Thread thread =  new Thread(null, viewOrders, "MagentoBackground");
		  	      thread.start();
		  	      m_ProgressDialog = ProgressDialog.show(FBLogin.this, "Please wait...", "Retrieving data ...", true);
            	}
        	});
        }

        public void onAuthFail(String error) {
        	//txtEstado.setText("Login Failed: " + error);
        }
    }

    public class SampleLogoutListener implements LogoutListener {
        public void onLogoutBegin() {
        	//txtEstado.setText("Logging out...");
        }

        public void onLogoutFinish() {
        	//txtEstado.setText("You have logged out! ");
            //mRequestButton.setVisibility(View.INVISIBLE);
            //mUploadButton.setVisibility(View.INVISIBLE);
            //mPostButton.setVisibility(View.INVISIBLE);
        }
    }    

    public class InfoRequestListener extends BaseRequestListener {

        public void onComplete(final String response, final Object state) {
            try {
                // process the response here: executed in background thread
                
            	
            	Log.d("Facebook-Example", "Response: " + response.toString());
                JSONObject json = Util.parseJson(response);
                
                final String uid 		= json.getString("id");
                final String nombre 	= json.getString("name");
                final Boolean esAdmin 	= (Config.FB_PAGE_ADMIN.equals(uid) ? true : false);
                final String nombreImagen = imagenFinal;
                
                FBLogin.this.runOnUiThread(new Runnable() {
                    
                	public void run() {
                		if(m_ProgressDialog!=null)
                			m_ProgressDialog.dismiss();
                        Bundle params = new Bundle();
                        params.putString	("uid"			, uid);
                        params.putString	("nombre"		, nombre);
                        params.putBoolean	("esAdmin"		, esAdmin);
                        params.putString	("ImagenUri"	, uri.toString());
                        params.putString	("nombreImagen"	, nombreImagen);
                        
                        Config.cambiarDePantalla(Config.PANTALLA_PUBLICAR_FOTO, params, FBLogin.this);
                        
                    }
                });
            } catch (JSONException e) {
                Log.w("Facebook-Example", "JSON Error in response");
            } catch (FacebookError e) {
                Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
            }
        }
    }
}
